import service from './http'
import urlList from './interface.js'
import { queryParams } from 'lib@/utils/utils'

function isNameExist(urlName) {
  return !urlList[urlName]
}

const http = {
  /**
 * get方法，对应get请求
 * @param {String} urlName [请求的url地址名称 对应interface中定义的key值]
 * @param {Object} params [请求时携带的参数]
 * @param {String} otherUrl [请求时额外url]
 */
  get: (urlName, params = {}, otherUrl = '') => {
    return new Promise((resolve, reject) => {
      if (isNameExist(urlName)) reject('接口未定义')
      service.get(`${urlList[urlName]}${otherUrl}`, { params: params })
        .then(res => { resolve(res) })
        .catch(err => { reject(err) })
    })
  },
  /**
   * post方法，对应post请求
   * @param {String} urlName [请求的url地址名称 对应interface中定义的key值]
   * @param {Object} params [请求时携带的参数]
   * @param {String} otherUrl [请求时额外url]
   * @param {Object} config [请求时额外传参]
  */
  post: (urlName, params, otherUrl = '', config = {}) => {
    return new Promise((resolve, reject) => {
      if (isNameExist(urlName)) reject('接口未定义')
      service.post(`${urlList[urlName]}${otherUrl}`, params, config)
        .then(res => { resolve(res) })
        .catch(err => { reject(err) })
    })
  },
  /**
   * put方法，对应put请求
   * @param {String} urlName [请求的url地址名称 对应interface中定义的key值]
   * @param {Object} params [请求时携带的参数]
   * @param {String} otherUrl [请求时额外url]
   * @param {Object} config [请求时额外传参]
  */
  put: (urlName, params, otherUrl = '', config = {}) => {
    return new Promise((resolve, reject) => {
      if (isNameExist(urlName)) reject('接口未定义')
      service.put(`${urlList[urlName]}${otherUrl}`, params, config)
        .then(res => { resolve(res) })
        .catch(err => { reject(err) })
    })
  },
  /**
   * delete方法，对应delete请求
   * @param {String} urlName [请求的url地址名称 对应interface中定义的key值]
   * @param {Object} params [请求时携带的url参数]
   * @param {String} otherOption [请求额外参数 【otherUrl: 额外携带的url】【 data：body参数】]
  */
  delete: (urlName, params = {}, otherOption) => {
    const oldOtherOption = {
      otherUrl: '',
      data: {}
    }
    let newOption = Object.assign(oldOtherOption, otherOption)
    let urlPamamsStr = queryParams(params)
    return new Promise((resolve, reject) => {
      if (isNameExist(urlName)) reject('接口未定义')
      service.delete(`${urlList[urlName]}${newOption.otherUrl}${urlPamamsStr}`, { data: newOption.data })
        .then(res => { resolve(res) })
        .catch(err => { reject(err) })
    })
  },
  /**
   * axios请求方法。可以更强的自定义扩展，具体查看axios文档。目前只是为了项目统一请求简单包装了一下。
   * @param {Object} config  axios请求里面参数
   * @returns 
   */
  request: (config) => {
    let oldConfig = {
      method:'get'
    }
    let newConfig= Object.assign(oldConfig,config)
    return new Promise((resolve, reject) => {
      if (isNameExist(newConfig.url)) reject('接口未定义')
      let url = urlList[newConfig.url]
      newConfig.url = url
      service(newConfig).then(res => { resolve(res) })
        .catch(err => { reject(err) })
    })

  }
}

export default http